package com.example.service;

import com.example.model.entity.Post;
import com.example.model.entity.User;
import com.example.repository.PostRepository;
import com.example.repository.LikeRepository;
import com.example.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private LikeRepository likeRepository;
    
    @Autowired
    private CommentRepository commentRepository;

    @Transactional
    public Post createPost(Post post, Long userId) {
        User user = userService.findById(userId);
        post.setUser(user);
        post.setCreatedAt(LocalDateTime.now());
        post.setUpdatedAt(LocalDateTime.now());
        return postRepository.save(post);
    }

    public Post findById(Long id) {
        return postRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("帖子不存在"));
    }

    public List<Post> findByUserId(Long userId) {
        return postRepository.findByUserId(userId);
    }

    @Transactional
    public Post updatePost(Long id, Post postDetails) {
        Post post = findById(id);
        post.setTitle(postDetails.getTitle());
        post.setContent(postDetails.getContent());
        post.setImageUrls(postDetails.getImageUrls());
        post.setUpdatedAt(LocalDateTime.now());
        return postRepository.save(post);
    }

    @Transactional
    public void deletePost(Long id) {
        postRepository.deleteById(id);
    }

    public Page<Post> findByCategory(String category, PageRequest pageRequest) {
        if (category != null && !category.isEmpty()) {
            return postRepository.findByCategory(category, pageRequest);
        }
        return postRepository.findAll(pageRequest);
    }

    public Page<Post> findByUserIdWithPage(Long userId, PageRequest pageRequest) {
        return postRepository.findByUserId(userId, pageRequest);
    }

    public long getLikesCount(Long postId) {
        return likeRepository.countByPostId(postId);
    }

    public long getCommentsCount(Long postId) {
        return commentRepository.countByPostId(postId);
    }

    public long getCollectsCount(Long postId) {
        return 0L;
    }

    // 查询用户收藏的帖子
    public Page<Post> findUserCollections(Long userId, PageRequest pageRequest) {
        return postRepository.findUserCollections(userId, pageRequest);
    }

    // 查询用户点赞的帖子
    public Page<Post> findUserLikedPosts(Long userId, PageRequest pageRequest) {
        //return postRepository.findUserLikedPosts(userId, pageRequest);
        return null;
    }
} 